package com.steven.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws Exception {
        //创建serverSocketChannel;
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //得到一个selector对象
        Selector selector = Selector.open();

        //绑定段端口。
        serverSocketChannel.socket().bind(new InetSocketAddress(7777));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //注册到selector。
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//        等待连接
        while (true){
            //等待一秒
            if(selector.select(1000)==0){
                //没有事件发生
                System.out.println("等待一秒无连接");
                continue;
            }
            //如果返回的不是0,获取相关集合，有关注事件发生的key的集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                //查看key关联的通道发生的事件做相应的处理
                if(selectionKey.isAcceptable()){

                    //给客户端生成socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    System.out.println("有新的客户端连接。。。。"+socketChannel.hashCode());
                    //注册到selector,关注的事件为读取 同时给channel关联一个buffer
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }else if(selectionKey.isReadable()){
                    System.out.println("有客户端发送数据。。。。");
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    //获取channel关联的buffer
                    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                    //读取数据
                    channel.read(byteBuffer);
                    System.out.println("客户端发送的数据："+new String(byteBuffer.array()));
                }
                iterator.remove();
            }

        }
    }
}
